package compound.repository

import compound.repository.entries.Compound
import util.ConvertHelper

class MassLookupController {

    /**
     * does the actual converting of data
     */
    ConvertService convertService
    DataExportService dataExportService = new DataExportService();

    def index =
        {
            String ids = ""
            String from = params.from
            def to = params.to

            log.info "from: ${from}"
            log.info "to: ${from}"


            if (session.getAttribute("ids") != null) {
                ids = session.getAttribute("ids").toString()
            }

            if (params.from != null) {
                from = params.from

            }

            if (params.to != null) {
                to = params.to
            }

            return [fromFields: ConvertHelper.getInstance().getFromConversions(), toFields: ConvertHelper.getInstance().getToConversions(), ids: ids, from: from, to: to]
        }

    /**
     * process list of ids and returns a map containning all the found Compounds
     */
    def masstransform =
        {


            String id = "transform_content"
            session[id] = null

            String from = params.from
            def StrTo = params.to
            String ids = ""


            if (params.ids != null) {
                ids = params.ids
                session.setAttribute("ids", ids);
            }
            else {
                ids = session.getAttribute("ids").toString()
            }

            if (ids == null || ids.trim().length() == 0) {
                flash.message = "Error! Ids parameter is mandatory, Please Enter some ids."
                redirect(action: "index")
            } else {
                if (from == null || from.toString().equalsIgnoreCase("NULL")) {
                    flash.message = "Error! From parameter is mandatory."
                    redirect(action: "index")
                } else {
                    if (StrTo == null) {
                        flash.message = "Error! To parameter is mandatory, Please select at least one."
                        redirect(action: "index")
                    }
                }
            }

            def to = []

            if (StrTo instanceof String) {
                to.add StrTo.trim()
            } else {
                StrTo.each {String s ->
                    to.add s.trim()
                }

            }
            // prepare the list of ids : Start
            def list = []

            int counter = 0;

            ids.split("\n").each {String s ->
                if (counter < 100) {
                    flash.message = "sorry we only allow up to 100 convertions at a time, please use the webservice API in case you like to convert more ids at once. All id's after 100 have been removed. This limitation is due to performance and stability reasons and will be waved in a future version of this tool"
                    list.add s.trim()

                    counter++
                }
            }
            // prepare the list of ids : End


            if (params?.format && params.format != "html") //Export
            {

                //call the service to conver the data
                Collection<Map<Compound, ?>> transform = convertService.convert(from, to, list)

                params.put("to", to);
                dataExportService.exportMassLookUp(transform, response, params)

            } else {
                if (params.offset == null || params.offset.toString().equals("0")) {
                    params.put("offset", 0);
                } else {
                    params.put("offset", Long.parseLong("0" + params.offset.toString()));
                }

                if (params.max == null || params.max.toString().equals("0")) {
                    params.put("max", 10);
                } else {
                    params.put("max", Long.parseLong("0" + params.max.toString()));
                }

                //call the service to to get Count of the data
                Long total = 0;
                if (params.total == null || params.total.toString().equals("0")) {
                    total = convertService.getCount(from, to, list)
                } else {
                    total = Long.parseLong(params.total.toString())
                }

                //call the service to conver the data
                Collection<Map<Compound, ?>> result = convertService.convert(from, to, list, params)

                session[id] = result

                log.info "this request is accessible under: ${id}"

                return [transform: result, ids: ids, from: from, to: to, idsList: list, max: params.max, offset: params.offset, total: total, session_id: id]
            }
        }

    /**
     * returns the provide formats
     */
    static List getFormats() {
        return ['xml', 'json']
    }

    def show_help_remote = {
        render """<div class="message">Please enter some Ids in a vertical style like<br> <br>C00001 <br>C00002 <br>C00003 <br>C00004 <br>C00005 <br>C00006</div>"""
    }

}
